package com.ddpt.permission.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Title: IpUtil.class
 * Description: 请求IP 工具类
 * <p>
 * Create DateTime: 2019-02-19 11:25
 *
 * @author zyf
 */
public class IpUtil {

    private static final String UNKNOWN = "unKnown";

    /**
     * 获取客户端请求的实际IP
     *
     * @param request HttpServletRequest
     * @return 客户端真实IP
     */
    public static String getRealRequestIp(HttpServletRequest request ) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index == -1) {
                return ip;
            }
            return ip.substring(0, index);
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
